import csv

# Maximum value map for each field, all value start with zero and populated by the Max number in the dataset
max_values = {
    "化羽": 0, "助攻": 0, "治疗": 0,
    "击杀": 0, "玩家伤害": 0, "建筑伤害": 0, "拆塔队塔伤": 0,
    "承伤": 0, "铁衣承伤": 0, "重伤": 0
}

def normalize(value, field):
    """Normalize a value to a 0-100 scale based on the maxValues map."""
    return (value / max_values[field]) * 100

def calculate_rating(row):
    """Calculate the total rating based on the type of form data provided."""
    total_rating = 0
    print(row)
    if row['\ufeff职业'] == '素问':  # 素问 version
        metrics = ['治疗', '承伤', '助攻', '化羽', '重伤'] 
        weights = [0.3, 0.2, 0.3, 0.2, -0.1]
        # total rating is the sum of all of the metrics above minus the value of 重伤 * weights
        total_rating = sum(normalize(float(row[m]), m) * w for m, w in zip(metrics, weights))
        # create statistics for each user where each of the metrics are the values normalized to 0-100
        statistics = {m: normalize(float(row[m]), m) for m in metrics if m != '重伤'}
        statistics['重伤'] = normalize(float(row['重伤']), '重伤') * weights[-1]
        
    elif row['\ufeff职业'] == 'DPS':  # DPS version
        metrics = ['玩家伤害', '承伤', '击杀', '助攻', '建筑伤害', '重伤']
        weights = [0.40, 0.10, 0.30, 0.10, 0.10, -0.10]
        total_rating = sum(normalize(float(row[m]), m) * w for m, w in zip(metrics, weights))
        statistics = {m: normalize(float(row[m]), m) for m in metrics if m != '重伤'}
        statistics['重伤'] = normalize(float(row['重伤']), '重伤') * weights[-1]

    elif row['\ufeff职业'] == '拆塔':  # 拆塔 version
        metrics = ['玩家伤害', '承伤', '击杀', '助攻', '拆塔队塔伤', '重伤']
        weights = [0.05, 0.10, 0.05, 0.20, 0.60, -0.05]
        total_rating = sum(normalize(float(row[m]), m) * w for m, w in zip(metrics, weights))
        statistics = {m: normalize(float(row[m]), m) for m in metrics if m != '重伤'}
        statistics['重伤'] = normalize(float(row['重伤']), '重伤') * weights[-1]

        
    elif row['\ufeff职业'] == '铁衣':  # 铁衣 version
        metrics = ['玩家伤害', '铁衣承伤', '击杀', '助攻', '建筑伤害', '重伤']
        weights = [0.20, 0.50, 0.05, 0.20, 0.05, -0.10]
        total_rating = sum(normalize(float(row[m]), m) * w for m, w in zip(metrics, weights))
        statistics = {m: normalize(float(row[m]), m) for m in metrics if m != '重伤'}
        statistics['重伤'] = normalize(float(row['重伤']), '重伤') * weights[-1]

    return total_rating, statistics

# Reading the CSV file and calculating ratings
def calculate_ratings_from_csv(csv_file):
    """Calculate ratings for each user in the CSV file."""
    # Open the CSV file to populate the max values first
    with open(csv_file, newline='') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            for field in max_values:
                max_values[field] = max(max_values[field], float(row[field]))
    
    # print the max values for each field
    # print(max_values)

    # Open the CSV file again to calculate the ratings
    # with open(csv_file, newline='') as csvfile:
    #     reader = csv.DictReader(csvfile)
    #     for row in reader:
    #         rating, stat = calculate_rating(row)
    #         # for each value in stat, round it to 2 decimal places
    #         stat = {k: round(v, 2) for k, v in stat.items()}
    #         print(f"职业: {row['职业']}, 昵称: {row['userId']}, {stat}, 总评分: {rating:.2f}")

    # Turn this output into a csv file, using the same format as the input csv file
    with open('bangzhan_ratings.csv', 'w', newline='') as csvfile:
        fieldnames = ["职业","userId","击杀","玩家伤害","助攻","承伤","铁衣承伤","建筑伤害", "拆塔队塔伤","治疗","化羽","重伤","总评分"]
        field_annotated = ["职业","昵称","击杀(总分100)","玩家伤害(总分100)","助攻(总分100)","承伤(总分100)","铁衣承伤(总分100)","建筑伤害(总分100)","拆塔队塔伤(总分100)","治疗(总分100)","化羽(总分100)","重伤(倒扣分值)","总评分"]
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames, extrasaction='ignore')
        writer.writerow(dict(zip(fieldnames, field_annotated)))  # write annotated fieldnames as headers

        with open(csv_file, newline='') as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                rating, stat = calculate_rating(row)
                # Add everything to stat before writing it to the csv file
                stat['总评分'] = rating
                stat = {k: round(v, 2) for k, v in stat.items()}
                # These two values cannot be rounded
                stat["职业"] = row["\ufeff职业"]
                stat["userId"] = row["userId"]
                # add the statistics to the row, but for anything not in the stat, add 0
                for k in fieldnames:
                    if k not in stat:
                        stat[k] = 0
                    row[k] = stat[k]
                writer.writerow(row)
        
        

# Example usage
csv_file = 'bangzhan_data.csv'  # Specify the path to your CSV file
calculate_ratings_from_csv(csv_file)